package com.lgy.common.base;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import java.lang.reflect.ParameterizedType;
import java.util.List;

public class BaseService<T> implements IBaseService<T> {
    private Class<T> cache = null;  //缓存子类泛型类型
    @Autowired
    private IBaseDao<T> mapper;

    @Override
    public Mapper<T> getMapper() {
        return mapper;
    }

    /**
     * 添加
     * @param t
     * @return
     */
    @Override
    public T add(T t){
        System.out.println(t);
        int i = mapper.insertSelective(t);
        if(i>0)
            return t;
        else
            return null;
    }

    /**
     * 删除 by 主键key
     * @param  t
     */
    @Override
    public void delete(T t){
        mapper.deleteByPrimaryKey(t);
    }

    /**
     * 通过主键集合批量删除
     * 数据库主键名必须为id
     * @param ids
     */
    @Override
    public int deleteByIds(List<Integer> ids){
        Example example=Example.builder(getTypeArguement()).where(Sqls.custom().andIn("id",ids)).build();
        return mapper.deleteByExample(example);
    }

    /**
     * 更新
     * @param t
     * @return
     */
    @Override
    public int update(T t){
        return  mapper.updateByPrimaryKeySelective(t);
    }

    /**
     * 查询List
     * @param t
     * @return
     */
    @Override
    public List<T> queryList(T t) {
        return mapper.select(t);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int batchSave(List<T> list) {
        return mapper.insertList(list);
    }

    /**
     * 获取子类泛型类型
     * @return
     */
    private Class<T> getTypeArguement() {
        if(cache == null)
            cache= (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return cache;
    }
}
